/**
 * 自定义Hooks【获取】问卷编辑页面 — 页面组件信息
 * @author 滕轶男
 */
import { useEffect, useState } from 'react'
import { useRequest } from 'ahooks'
import { useParams } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { getQuestionServices } from '../services/question'
import { resetComponents } from '../store/componentsReducer'
import { resetPageInfo } from '../store/pageInfoReducer'

function useLoadQuestionData() {
    const { id = '' } = useParams()
    const dispatch = useDispatch()
    const { data, loading, error, run } = useRequest(
        async (id: string) => {
            if (!id) throw new Error('没有问卷ID')
            const data = await getQuestionServices(id)
            return data
        },
        {
            manual: true,
        }
    )

    // 根据获取的 data 设置 redux store
    useEffect(() => {
        if (!data) return
        // 解构接口返回的数据
        const {
            componentsList = [],
            title = '',
            desc = '',
            js = '',
            css = '',
            isPublished = false,
        } = data
        // 获取默认的selectedId
        let selectedId = ''
        if (componentsList.length > 0) {
            selectedId = componentsList[0].fe_id
        }
        // 把 componentsList 存储到redux store中
        dispatch(resetComponents({ componentsList, selectedId, copiedComponent: null }))
        // 把页面信息存储到redux的store中
        dispatch(resetPageInfo({ title, desc, js, css, isPublished }))
    }, [data])
    // 判断ID变化执行Ajax加载问卷数据
    useEffect(() => {
        run(id)
    }, [id])

    return { loading, error }
}
export default useLoadQuestionData
